<template>
	<view>
		<view class="tabs">
			<view class="tab-item" :class="{ 'active': activeTab === 'unused' }" @click="switchTab('unused')">未使用</view>
			<view class="tab-item" :class="{ 'active': activeTab === 'used' }" @click="switchTab('used')">已使用</view>
		</view>

		<view v-if="activeTab === 'unused'">
			<view class='reward-list' v-if="rewardList.length">
				<view class='item acea-row row-center-wrapper' v-for='(item,index) in rewardList' :key="index" @click="showRedemptionQrCode(item.redemptionCode)">
					<view class='text'>
						<view class='condition line2'>
							<span>{{item.prizeName}}</span>
						</view>
						<view class='data acea-row row-between-wrapper'>
							<view>奖品描述: {{item.prizeValue}}</view>
							<view>兑换码: {{item.redemptionCode}}</view>
						</view>
						<view class='data acea-row row-between-wrapper'>
							<view>中奖时间: {{item.createTime}}</view>
							<view :class="{'verified': item.isVerified, 'unverified': !item.isVerified}">{{ item.isVerified ? '已兑换' : '未兑换' }}</view>
						</view>
					</view>
				</view>
			</view>
			<view class='loadingicon acea-row row-center-wrapper' v-if="rewardList.length">
				 <text class='loading iconfont icon-jiazai' :hidden='loading==false'></text>{{loadTitle}}
			  </view>
			<view class='noCommodity' v-if="!rewardList.length">
				<view class='pictrue'>
					<image src='../../../static/images/noReward.png'></image>
				</view>
				<text>暂无中奖奖励</text>
			</view>
		</view>

		<view v-if="activeTab === 'used'">
			<view class='reward-list' v-if="rewardList.length">
				<view class='item acea-row row-center-wrapper' v-for='(item,index) in rewardList' :key="index">
					<view class='text'>
						<view class='condition line2'>
							<span>{{item.prizeName}}</span>
						</view>
						<view class='data acea-row row-between-wrapper'>
							<view>奖品描述: {{item.prizeValue}}</view>
						</view>
						<view class='data acea-row row-between-wrapper'>
							<view>中奖时间: {{item.createTime}}</view>
						</view>
					</view>
				</view>
			</view>
			<view class='loadingicon acea-row row-center-wrapper' v-if="rewardList.length">
				 <text class='loading iconfont icon-jiazai' :hidden='loading==false'></text>{{loadTitle}}
			  </view>
			<view class='noCommodity' v-if="!rewardList.length">
				<view class='pictrue'>
					<image src='../../../static/images/noReward.png'></image>
				</view>
				<text>暂无中奖奖励</text>
			</view>
		</view>

		<!-- #ifdef MP -->
		<!-- <authorize @onLoadFun="onLoadFun" :isAuto="isAuto" :isShowAuth="isShowAuth" @authColse="authColse"></authorize> -->
		<!-- #endif -->
		<home></home>

		<simple-modal ref="qrCodeModal" title="兑换码二维码" @close="closeQrCodeModal">
			<view class="qrcode-container">
				<canvas canvas-id="qrcode" :style="{ width: qrcodeSize + 'px', height: qrcodeSize + 'px' }"></canvas>
				<text class="redemption-code-text">{{ currentRedemptionCode }}</text>
			</view>
		</simple-modal>
	</view>
</template>

<script>
	import {
		getMyWonPrizes
	} from '@/api/draw.js';
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		mapGetters
	} from "vuex";
	// #ifdef MP
	import authorize from '@/components/Authorize';
	// #endif
	import home from '@/components/home';
	import simpleModal from '@/components/common/simple-modal.vue';
	import uQRCode from '@/js_sdk/Sansnn-uQRCode/uqrcode.js';

	export default {
		components: {
			// #ifdef MP
			authorize,
			// #endif
			home,
			simpleModal
		},
		data() {
			return {
				activeTab: 'unused',
				allRewardList: [], // To store all fetched rewards
				unusedList: [],
				usedList: [],
				rewardList: [], // This will be the currently displayed list based on activeTab
				loading: false,
				loadend: false,
				loadTitle: '加载更多', //提示语
				page: 1,
				limit: 20,
				isAuto: false, //没有授权的不会自动授权
				isShowAuth: false, //是否隐藏授权
				showQrCodeModal: false,
				currentRedemptionCode: '',
				qrcodeSize: 200, // 二维码尺寸
			};
		},
		computed: mapGetters(['isLogin']),
		watch: {
			isLogin: {
				handler: function(newV, oldV) {
					if (newV) {
						this.loadRewardList();
					}
				},
				deep: true
			}
		},
		onLoad() {
			if (this.isLogin) {
				this.loadRewardList();
			} else {
				toLogin();
			}
		},
		methods: {
			switchTab(tab) {
				if (this.activeTab === tab) return;
				this.activeTab = tab;
				// Filter the already loaded data
				this.rewardList = (this.activeTab === 'unused' ? this.unusedList : this.usedList);
				// If the current list is empty and there might be more data, load more
				if (this.rewardList.length === 0 && !this.loadend) {
					this.loadRewardList();
				}
			},
			/**
			 * 授权回调
			 */
			onLoadFun: function() {
				this.loadRewardList();
			},
			// 授权关闭
			authColse: function(e) {
				this.isShowAuth = e
			},
			/**
			 * 获取用户中奖实物奖品列表
			 */
			loadRewardList: function() {
				let that = this;
				if (this.loadend) return false;
				if (this.loading) return false;
				this.loading = true;
				getMyWonPrizes({
					page: that.page,
					limit: that.limit,
				}).then(res => {
					let list = res.data || [];
					that.allRewardList = that.$util.SplitArray(list, that.allRewardList);

					// Filter into unused and used lists
					that.unusedList = that.allRewardList.filter(item => !item.isVerified);
					that.usedList = that.allRewardList.filter(item => item.isVerified);

					// Update rewardList based on activeTab for display
					that.rewardList = (that.activeTab === 'unused' ? that.unusedList : that.usedList);

					that.loadend = list.length < that.limit;
					that.loadTitle = that.loadend ? '我也是有底线的' : '加载更多';
					that.page = that.page + 1;
					that.loading = false;
				}).catch(err => {
					that.loading = false;
					that.loadTitle = '加载更多';
					console.error("获取奖励列表失败", err);
				});
			},
			/**
			 * 显示兑换码二维码
			 */
			showRedemptionQrCode(code) {
				if (!code) {
					uni.showToast({
						title: '兑换码为空',
						icon: 'none'
					});
					return;
				}
				this.currentRedemptionCode = code;
				this.$refs.qrCodeModal.open();
				// 确保canvas渲染完成后再绘制二维码
				this.$nextTick(() => {
					console.log("Drawing QR code for: ", this.currentRedemptionCode);
					console.log("QR code size: ", this.qrcodeSize);
					this.drawQrCode();
				});
			},
			/**
			 * 绘制二维码
			 */
			drawQrCode() {
				// 确保在绘制前获取正确的canvas上下文
				const ctx = uni.createCanvasContext('qrcode', this);
				ctx.clearRect(0, 0, this.qrcodeSize, this.qrcodeSize);
				ctx.draw(false, () => {
					uQRCode.make({
						canvasId: 'qrcode',
						componentInstance: this,
						text: this.currentRedemptionCode,
						size: this.qrcodeSize,
						margin: 10,
						backgroundColor: '#ffffff',
						foregroundColor: '#000000',
														errorCorrectLevel: 2,
													success: () => {
														console.log("QR code drawn successfully!");
													},
													fail: (error) => {
														console.error("Failed to draw QR code:", error);
													}
												});				});
			},
			/**
			 * 关闭二维码弹窗
			 */
			closeQrCodeModal() {
				this.currentRedemptionCode = '';
				// 清除canvas内容，避免下次打开时显示旧的二维码
				const ctx = uni.createCanvasContext('qrcode', this);
				ctx.clearRect(0, 0, this.qrcodeSize, this.qrcodeSize);
				ctx.draw();
			},
		},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {
			this.loadRewardList();
		}
	}
</script>

<style lang="scss" scoped>
	.tabs {
		display: flex;
		justify-content: space-around;
		background-color: #fff;
		border-bottom: 1rpx solid #eee;
		.tab-item {
			padding: 20rpx 0;
			color: #666;
			&.active {
				color: #333;
				font-weight: bold;
				border-bottom: 2rpx solid #333;
			}
		}
	}
	.reward-list {
		padding: 20rpx;

		.item {
			background-color: #fff;
			border-radius: 10rpx;
			margin-bottom: 20rpx;
			padding: 20rpx;
			display: flex;
			flex-direction: column;

			.text {
				width: 100%;
			}

			.condition {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 10rpx;
			}

			.data {
				font-size: 28rpx;
				color: #666;
				margin-top: 5rpx;
			}
			.verified {
				color: #00C250;
			}
			.unverified {
				color: #00C250;
			}
		}
	}

	.noCommodity {
		margin-top: 300rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #999;
		font-size: 28rpx;

		.pictrue {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 20rpx;

			image {
				width: 100%;
				height: 100%;
			}
		}
	}

	.qrcode-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 20rpx;

		canvas {
			border: 1rpx solid #eee;
		}

		.redemption-code-text {
			margin-top: 20rpx;
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}
	}
</style>
